<template>
  <el-dialog v-model="dialogVisible" title="合同详情" width="70%">
    <div v-loading="loading">
      <el-descriptions :column="2" border>
        <el-descriptions-item label="合同编号">{{ currentContract.contractNumber || '暂无' }}</el-descriptions-item>
        <el-descriptions-item label="合同名称">{{ currentContract.title || '暂无' }}</el-descriptions-item>
        <el-descriptions-item label="申请人">{{ currentContract.applicant || '暂无' }}</el-descriptions-item>
        <el-descriptions-item label="合同类型">{{ currentContract.contractType || '暂无' }}</el-descriptions-item>
        <el-descriptions-item label="企业名称">{{ currentContract.companyName || '暂无' }}</el-descriptions-item>
        <el-descriptions-item label="企业地址">{{ currentContract.companyAddress || '暂无' }}</el-descriptions-item>
        <el-descriptions-item label="合同租期">
          {{ formatContractPeriod(currentContract.startDate, currentContract.endDate) }}
        </el-descriptions-item>
        <el-descriptions-item label="合同状态">
          <el-tag :type="getStatusType(currentContract.contractStatus)">
            {{ currentContract.contractStatus || '暂无' }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="创建时间">{{ currentContract.createdAt || '暂无' }}</el-descriptions-item>
        <el-descriptions-item label="更新时间">{{ currentContract.updatedAt || '暂无' }}</el-descriptions-item>
        
        <!-- 条件显示拒绝原因 -->
        <el-descriptions-item v-if="currentContract.rejectReason" label="拒绝原因">
          <el-alert :title="currentContract.rejectReason" type="error" :closable="false" />
        </el-descriptions-item>
        
        <!-- 添加附件显示 -->
        <el-descriptions-item label="合同附件">
          <div v-if="currentContract.attachments && currentContract.attachments.length">
            <div v-for="(file, index) in currentContract.attachments" :key="index" class="attachment-item">
              <el-link :href="file.url" target="_blank" type="primary">
                {{ file.name }} ({{ formatFileSize(file.size) }})
              </el-link>
            </div>
          </div>
          <span v-else>暂无附件</span>
        </el-descriptions-item>
      </el-descriptions>
    </div>
  </el-dialog>
</template>

<script setup>
import { ref } from 'vue'
import { ElMessage } from 'element-plus'
import axios from 'axios'

// 创建axios实例
const api = axios.create({
  baseURL: import.meta.env.VITE_API_BASE_URL,
  timeout: 5000
})

// 格式化文件大小
const formatFileSize = (bytes) => {
  if (!bytes) return '未知大小'
  if (bytes === 0) return '0 Bytes'
  const k = 1024
  const sizes = ['Bytes', 'KB', 'MB', 'GB']
  const i = Math.floor(Math.log(bytes) / Math.log(k))
  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
}

// 状态类型判断
const getStatusType = (status) => {
  switch (status) {
    case '已签署': return 'success'
    case '待审批': return 'warning'
    case '已逾期': return 'danger'
    case '已终止': return 'info'
    default: return 'primary'
  }
}

const dialogVisible = ref(false)
const currentContract = ref({})
const loading = ref(false)

// 加载单个合同详情
const loadContractDetail = async (id) => {
  loading.value = true
  try {
    const response = await api.get(`/api/contracts/${id}/with-attachments`)
    
    if (response.data && response.data.success) {
      currentContract.value = response.data.data
      console.log('合同详情数据:', response.data.data)
    } else {
      ElMessage.error('获取合同详情失败: ' + (response.data?.message || '未知错误'))
    }
  } catch (error) {
    console.error('加载合同详情失败:', error)
    if (error.response) {
      // 服务器返回错误状态码
      ElMessage.error(`获取合同详情失败: ${error.response.data?.message || error.response.status}`)
    } else if (error.request) {
      // 请求发送但没有收到响应
      ElMessage.error('网络连接失败，请检查后端服务是否启动')
    } else {
      // 其他错误
      ElMessage.error('加载合同详情失败: ' + error.message)
    }
  } finally {
    loading.value = false
  }
}

// 修改open方法
const open = async (row) => {
  console.log('接收到的合同数据:', row)
  dialogVisible.value = true
  loading.value = true
  
  // 先显示基本信息
  currentContract.value = {
    ...row,
    companyAddress: row.companyAddress || '暂无',
    contractNumber: row.contractNumber || '暂无',
    title: row.title || '暂无',
    applicant: row.applicant || '暂无',
    companyName: row.companyName || '暂无',
    contractType: row.contractType || '暂无',
    startDate: row.startDate || '暂无',
    endDate: row.endDate || '暂无',
    contractStatus: row.contractStatus || '暂无',
    attachments: row.attachments || [],
    rejectReason: row.rejectReason || null
  }
  
  if (row.id) {
    await loadContractDetail(row.id)
  } else {
    loading.value = false
  }
}

// 格式化合同租期显示
const formatContractPeriod = (startDate, endDate) => {
  if (!startDate || !endDate) return '暂无'
  
  const formatDate = (dateStr) => {
    try {
      const date = new Date(dateStr)
      return `${date.getFullYear()}/${String(date.getMonth() + 1).padStart(2, '0')}/${String(date.getDate()).padStart(2, '0')}`
    } catch (e) {
      return dateStr
    }
  }
  
  return `${formatDate(startDate)} 至 ${formatDate(endDate)}`
}

defineExpose({ open })
</script>

<style scoped>
.attachment-item {
  margin-bottom: 8px;
  display: flex;
  align-items: center;
}

.attachment-item .el-link {
  margin-right: 10px;
}

/* 为拒绝原因添加特殊样式 */
:deep(.el-descriptions-item__content) .el-alert {
  margin: 0;
  padding: 8px;
}

/* 加载状态样式 */
.loading-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(255, 255, 255, 0.8);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}
</style>